﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using Model;

namespace TanHungLong
{
    public partial class FrmPhieuTra : DevExpress.XtraEditors.XtraForm
    {
        #region variant
        private FormStatus formStatus = FormStatus.View;
        private bool allowCloseForm = true;
        private GiaBOCollection giaBOCollection = null;
        private NhomHangBOCollection nhomHangBOCollection = null;
        private TraHangBOCollection TraHangBOCollection = TraHangBOCollection.NewTraHangBOCollection();
        

        private string COLUMN_FIRST_MatHang = "Ten";
        private string COLUMN_SECOND_MatHang = "SoThuTu";

        private string COLUMN_FIRST_PhieuNhapChiTiet = "Ten";
        private string COLUMN_SECOND_PhieuNhapChiTiet = "HeSo";
        #endregion variant

        //=====================================
        #region form
        public FrmPhieuTra()
        {
            InitializeComponent();
            this.KeyPreview = true;

            this.Load += new EventHandler(FrmPhieuTra_Load);
            this.Shown += new EventHandler(FrmPhieuTra_Shown);
            this.FormClosing += new FormClosingEventHandler(FrmPhieuTra_FormClosing);
            this.grdViewPhieuNhapChiTiet.KeyDown += new KeyEventHandler(this.FrmHoadonnhap_KeyDown);
            this.txtTimkiem.KeyDown += new KeyEventHandler(this.txtTimkiem_KeyDown);
            this.grdViewMatHang.KeyDown += new KeyEventHandler(this.grdViewMatHang_KeyDown);
            this.KeyDown += new KeyEventHandler(FrmPhieuTra_KeyDown);

            this.btnAdd.Click += new EventHandler(btnAdd_Click);
            this.btnSave.Click += new EventHandler(btnSave_Click);
            this.btnClose.Click += new EventHandler(btnClose_Click);
            this.btnRefreshMatHang.Click += new EventHandler(btnRefreshMatHang_Click);


            this.grdViewMatHang.DoubleClick += new System.EventHandler(this.grdViewMatHang_DoubleClick);

            this.grdViewMatHang.RowCellStyle += new RowCellStyleEventHandler(grdView_RowCellStyle);
            this.grdViewPhieuNhapChiTiet.RowCellStyle += new RowCellStyleEventHandler(grdView_RowCellStyle);

            this.grdViewMatHang.ShowingEditor += new CancelEventHandler(grdView_ShowingEditor);
            this.grdViewPhieuNhapChiTiet.ShowingEditor += new CancelEventHandler(grdView_ShowingEditor);
            this.lookUpEditNhaCungCap.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(lookUpEditKhachHang_ButtonClick);
            this.lookUpMaKhachHang.EditValueChanged += new EventHandler(lookUpMaKhachHang_EditValueChanged);
        }

        void FrmPhieuTra_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.N && Control.ModifierKeys == Keys.Control)
                AddNew();
            if ((e.KeyCode == Keys.Q && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F10))
                this.Close();
            if ((e.KeyCode == Keys.R && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F5))
                RefreshData();
            if ((e.KeyCode == Keys.S && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F6))
                Save();
        }

        void lookUpMaKhachHang_EditValueChanged(object sender, EventArgs e)
        {
            lookUpEditNhaCungCap.EditValue = lookUpMaKhachHang.EditValue;
        }

        private void FrmPhieuTra_Shown(object sender, EventArgs e)
        {
            this.lookUpEditNhaCungCap.Focus();
        }

        private void FrmPhieuTra_Load(object sender, EventArgs e)
        {

            dtNgayLapHoaDon.DateTime = Session.NgayHeThong;

            Utility.InitControl(this.reLookUpMatHangID);
            Utility.InitControl(this.reLookUpDonViTinhID);

            Utility.InitControl(this.reLookUpMatHang);
            Utility.InitControl(this.reLookUpDonViTinh);
            Utility.InitControl(this.reLookUpDMKhoID);

            Utility.InitControl(this.lookUpNo, "StrSoHieu", "StrSoHieu");
            Utility.InitControl(this.lookUpCo, "StrSoHieu", "StrSoHieu");

            this.grdViewMatHang.FocusedRowChanged += new FocusedRowChangedEventHandler(grdViewMatHang_FocusedRowChanged);
            this.grdView.FocusedRowChanged += new FocusedRowChangedEventHandler(grdView_FocusedRowChanged);
            this.txtTimkiem.EditValueChanged += new System.EventHandler(this.txtTimkiem_EditValueChanged);

            this.grdViewPhieuNhapChiTiet.CellValueChanged += new CellValueChangedEventHandler(this.grdViewPhieuNhapChiTiet_CellValueChanged);

            RefreshData();


            SoHieuTaiKhoanBOCollection soHieuTaiKhoanBOCollection = SoHieuTaiKhoanBOCollection.GetSoHieuTaiKhoanBOCollection();
            soHieuTaiKhoanBOCollection.Sort();
            Utility.SetData(this.lookUpNo, soHieuTaiKhoanBOCollection, soHieuTaiKhoanBOCollection.Count);
            Utility.SetData(this.lookUpCo, soHieuTaiKhoanBOCollection, soHieuTaiKhoanBOCollection.Count);

            this.lookUpNo.EditValue = "131";
            this.lookUpCo.EditValue = "531";
        }

        private void FrmPhieuTra_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.allowCloseForm == false)
                e.Cancel = true;
        }

        private void FrmHoadonnhap_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyData == Keys.Delete)
            {
                int _idMatHang = StaticUtil.GetInt(this.grdViewPhieuNhapChiTiet.GetFocusedRowCellValue("STT0"), -1);
                if (_idMatHang >= 1)
                {
                    DeleteMatHang();
                }
                else
                {
                    MessageBox.Show("Bạn chưa chọn Vật tư để xóa! Vui lòng chọn lại", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.grdViewPhieuNhapChiTiet.Focus();
                }
            }
        }
        #endregion form

        //=====================================
        #region control

        private void txtTimkiem_EditValueChanged(object sender, EventArgs e)
        {
            FilterMatHangByName(txtTimkiem.Text.Trim());
        }


        private void spinEditTienPhatSinh_ValueChanged(object sender, EventArgs e)
        {
            TinhTien();
        }


        void lookUpEditKhachHang_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1)
            {
                FrmNewKhachHang.daluu = 0;
                FrmNewKhachHang frNewKH = new FrmNewKhachHang();
                frNewKH.ShowDialog();
                if (FrmNewKhachHang.daluu == 1)
                {
                    KhachHangBOCollection nn = KhachHangBOCollection.GetKhachHangBOCollection();
                    bdSourceNhaCungCap.DataSource = nn.Clone();
                    lookUpEditNhaCungCap.EditValue = lookUpMaKhachHang.EditValue = StaticUtil.GetInt(FrmNewKhachHang.KhachHangBO.KhachHangID, -1);
                    FrmNewKhachHang.daluu = 0;
                }
            }
            else
                if (e.Button.Index == 2)
                    lookUpEditNhaCungCap.EditValue = null;
        }
        #endregion control

        //=====================================
        #region button
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void btnRefreshMatHang_Click(object sender, EventArgs e)
        {
            FilterMatHangByName("");
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddNew();
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion button

        //=====================================
        #region grid
        private void grdViewMatHang_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            //FilterMatHang();
        }

        private void grdView_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            FilterMatHang();
        }

        private void grdView_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView grdView = (GridView)sender;

            bool del = StaticUtil.GetBool(grdView.GetFocusedRowCellValue("DELE"));
            string fieldName = grdView.FocusedColumn.FieldName;

            if (del && fieldName != "DELE")
                e.Cancel = true;
            else
                if (fieldName == "DELE" && grdView.FocusedRowHandle == GridControl.NewItemRowHandle)
                    e.Cancel = true;
        }

        private void grdView_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            bool del = StaticUtil.GetBool(this.grdViewMatHang.GetRowCellValue(e.RowHandle, "DELE"));

            if (del)
            {
                e.Appearance.Font = MyStyle.DELETE_FONT;
                e.Appearance.ForeColor = MyStyle.DELETE_COLOR;
            }
        }

        private void grdViewMatHang_DoubleClick(object sender, EventArgs e)
        {
            UpdatePhieuNhap();
        }

        private void grdViewPhieuNhapChiTiet_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {                
                sapxep();
                TinhTien();
            }
            catch { }
        }
        #endregion grid

        //=====================================
        #region function
        private void FilterMatHang()
        {
            Session.NhomHangID = StaticUtil.GetRealInt(this.grdView.GetFocusedRowCellValue("NhomHangID"));

            if (Session.NhomHangID == -1)
            {
                //this.grdViewPhieuNhapChiTiet.ActiveFilterString = "MatHangID=" + int.MaxValue;

                this.giaBOCollection = GiaBOCollection.GetGiaBOCollection();
                this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
            }
            else
            {
                MatHangBOCollection matHangBOCollection = MatHangBOCollection.GetMatHangBOCollection("NhomHangID = " + Session.NhomHangID.ToString());
                string strWhere = "";
                string listID = "";
                int recordCount = matHangBOCollection.Count;
                if (recordCount > 0)
                {
                    for (int i = 0; i < recordCount; i++)
                    {
                        object _idVattu = matHangBOCollection[i].MatHangID;
                        listID += _idVattu.ToString() + ",";
                    }
                }
                strWhere = strWhere + " MatHangID in ('" + listID.Replace(",", "','") + "')";
                this.giaBOCollection = GiaBOCollection.GetGiaBOCollection(strWhere);
                this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
            }

        }

        private void FilterMatHangByName(string nameMatHang)
        {
            MatHangBOCollection matHangBOCollection = MatHangBOCollection.GetMatHangBOCollection(" Ten like N'%" + nameMatHang + "%' or MaMatHang like N'%" + nameMatHang + "%'");
            string strWhere = "";
            string listID = "";
            int recordCount = matHangBOCollection.Count;
            if (recordCount > 0)
            {
                for (int i = 0; i < recordCount; i++)
                {
                    object _idVattu = matHangBOCollection[i].MatHangID;
                    listID += _idVattu.ToString() + ",";
                }
            }
            strWhere = strWhere + " MatHangID in ('" + listID.Replace(",", "','") + "')";
            this.giaBOCollection = GiaBOCollection.GetGiaBOCollection(strWhere);
            this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
        }

        private void ResetData()
        {
            lookUpEditNhaCungCap.EditValue = null;
            lookUpMaKhachHang.EditValue = null;
            dtNgayLapHoaDon.DateTime = Session.NgayHeThong;
            txtMaSo.Text = "TH-" + Session.NgayHeThong.ToString("dd/MM/yyyy") + "-" + DateTime.Now.ToString("HH:mm:ss");

            dtNgayLapHoaDon.DateTime = DateTime.Now;
            this.TraHangBOCollection = Model.TraHangBOCollection.NewTraHangBOCollection();
            sapxep();
            TinhTien();
            bdSourcePhieuNhapChiTiet.DataSource = this.TraHangBOCollection.Clone();
        }

        private void RefreshData()
        {
            #region

            DanhMucBOList donViTinhBOList = DanhMucBOList.GetDanhMucBOList(LoaiDanhMuc.DonViTinh);
            Utility.SetData(this.reLookUpDonViTinh, donViTinhBOList, donViTinhBOList.Count);
            Utility.SetData(this.reLookUpDonViTinhID, donViTinhBOList, donViTinhBOList.Count);

            DanhMucBOList dmKhoBOList = DanhMucBOList.GetDanhMucBOList(LoaiDanhMuc.DanhMucKho);
            Utility.SetData(this.reLookUpDMKhoID, dmKhoBOList, dmKhoBOList.Count);

            MatHangBOList matHangBOList = MatHangBOList.GetMatHangBOList();
            Utility.SetData(this.reLookUpMatHang, matHangBOList, matHangBOList.Count);
            Utility.SetData(this.reLookUpMatHangID, matHangBOList, matHangBOList.Count);

            KhachHangBOCollection khachHangBOColl = KhachHangBOCollection.GetKhachHangBOCollection("KH = 1");
            bdSourceNhaCungCap.DataSource = khachHangBOColl.Clone();

            #endregion BOList

            this.nhomHangBOCollection = NhomHangBOCollection.GetNhomHangBOCollection();

            NhomHangBO NewNhomHangBO = NhomHangBO.NewRootNhomHangBO();
            NewNhomHangBO.Ten = "Tất cả";
            NewNhomHangBO.NhomHangID = -1;
            this.nhomHangBOCollection.Add(NewNhomHangBO);

            this.bdSourceNhomHang.DataSource = this.nhomHangBOCollection.Clone();

            ResetData();

            FilterMatHang();
        }

        private void Edit()
        {
            this.formStatus = FormStatus.Edit;
            //SetFormStatus(this.formStatus);
            Session.CloseIndex++;
        }

        private void AddNew()
        {
            RefreshData();
        }

        private void Save()
        {
            if (kiemtraLuu() == 1)
            {

                //Thanh toán trả hàng
                KhachHangBO khachHangBO = KhachHangBO.GetRootKhachHangBO(StaticUtil.GetInt( this.lookUpEditNhaCungCap.EditValue,-1));
                if (khachHangBO == null)
                    khachHangBO = KhachHangBO.NewRootKhachHangBO();

                ThuChiBO thuChiBO = ThuChiBO.NewRootThuChiBO();
                thuChiBO.LoaiPhieu = 0; //chi
                thuChiBO.NgayLapPhieu = this.dtNgayLapHoaDon.DateTime;
                thuChiBO.NgayKyNhan = DateTime.Now;
                thuChiBO.HoaDonBanID = -1;
                thuChiBO.So = this.txtMaSo.Text.Trim();
                thuChiBO.Co = StaticUtil.GetString(this.lookUpCo.EditValue, null);
                thuChiBO.No = StaticUtil.GetString(this.lookUpNo.EditValue, null);
                thuChiBO.KhachHangID = StaticUtil.GetInt(this.lookUpEditNhaCungCap.EditValue, -1);
                thuChiBO.LaKhachHang = true;
                thuChiBO.HoTen = khachHangBO.Ten;
                thuChiBO.SoTien = (double)this.spinEditThanhTienTraLai.Value;
                thuChiBO.DaNhanDuSoTien = StaticUtil.ConvertMoney2Str(thuChiBO.SoTien);
                thuChiBO.DaKhoa = false;
                thuChiBO.NguoiNopTien = thuChiBO.HoTen;
                thuChiBO.DiaChi = khachHangBO.Diachi;
                thuChiBO.LyDo = "Khách hàng" + lookUpEditNhaCungCap.Text.Trim() + "Trả hàng";
                thuChiBO = thuChiBO.Save();

                //---------------------

                int recordCount = this.TraHangBOCollection.Count;
                if (recordCount > 0)
                {
                    for (int i = 0; i < recordCount; i++)
                    {
                        if (StaticUtil.GetDouble(this.TraHangBOCollection[i].SoLuong,0) > 0)
                        {
                            TonKhoBO tonKhoBO = null;
                            int matHangID = StaticUtil.GetInt(this.TraHangBOCollection[i].MatHangID, -1);
                            int donViTinhID = StaticUtil.GetInt(this.TraHangBOCollection[i].DonViTinhIDN, -1);
                            int danhMucKhoID = StaticUtil.GetInt(this.TraHangBOCollection[i].KhoID, -1);
                            tonKhoBO = TonKhoBO.GetRootTonKhoBOByWhere("(MatHangID = " + matHangID.ToString()
                                + ") and (DonViTinhID = " + donViTinhID.ToString()
                                + ") and (DanhMucKhoID = " + danhMucKhoID.ToString() + ")");
                            if (StaticUtil.GetInt(tonKhoBO.TonKhoID.Value, -1) < 0) tonKhoBO = TonKhoBO.NewRootTonKhoBO();
                            tonKhoBO.MatHangID = matHangID;
                            tonKhoBO.DonViTinhID = donViTinhID;
                            tonKhoBO.DanhMucKhoID = danhMucKhoID;
                            tonKhoBO.SoLuongTon = StaticUtil.GetDouble(tonKhoBO.SoLuongTon, 0) + StaticUtil.GetDouble(this.TraHangBOCollection[i].SoLuong, 0);
                            tonKhoBO.Save();
                            MaVachBO maVachBO = null;
                            string strWhere = "MaVach = '" + this.TraHangBOCollection[i].MaVach.ToString()
                                + "' and TonKhoID = " + StaticUtil.GetInt(tonKhoBO.TonKhoID.Value, -1).ToString();
                            maVachBO = MaVachBO.GetRootMaVachBOByWhere(strWhere);
                            if (StaticUtil.GetInt(maVachBO.MaVachID.Value, -1) < 0) maVachBO = MaVachBO.NewRootMaVachBO();
                            maVachBO.TonKhoID = StaticUtil.GetInt(tonKhoBO.TonKhoID.Value, -1);
                            maVachBO.MaVach = this.TraHangBOCollection[i].MaVach.ToString();
                            maVachBO.SoLuongTon = StaticUtil.GetDouble(maVachBO.SoLuongTon, 0) + StaticUtil.GetDouble(this.TraHangBOCollection[i].SoLuong, 0);
                            maVachBO.Save();

                            TraHangBO traHangBO = TraHangBO.NewRootTraHangBO();
                            traHangBO.KhachHangID = StaticUtil.GetInt(this.lookUpEditNhaCungCap.EditValue,-1);
                            traHangBO.MaSo = this.txtMaSo.Text.Trim();
                            traHangBO.MatHangID = matHangID;
                            traHangBO.DonViTinhIDN = donViTinhID;
                            traHangBO.KhoID = danhMucKhoID;
                            traHangBO.SoLuong = StaticUtil.GetDouble(this.TraHangBOCollection[i].SoLuong, 0);
                            traHangBO.ThanhTienTra = StaticUtil.GetDouble(this.TraHangBOCollection[i].ThanhTienTra, 0);
                            traHangBO.DienGiai = this.TraHangBOCollection[i].DienGiai;
                            traHangBO.Save();

                        }
                    }
                }
                MessageBox.Show("Trả Hàng Thành Công");
                AddNew();
            }

        }

        private void Cancel()
        {
            this.formStatus = FormStatus.View;
            //SetFormStatus(this.formStatus);
            Session.CloseIndex--;

            this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
            this.bdSourcePhieuNhapChiTiet.DataSource = this.TraHangBOCollection.Clone();

            FilterMatHang();
        }

        private void UpdatePhieuNhap()
        {
            int matHangID = StaticUtil.GetInt(grdViewMatHang.GetFocusedRowCellValue("MatHangID"));
            int donViTinhID = StaticUtil.GetInt(grdViewMatHang.GetFocusedRowCellValue("DonViTinhID"));
            TraHangBO newBO = TraHangBO.NewRootTraHangBO();
            newBO.MatHangID = matHangID;
            newBO.MaVach = "0";
            newBO.DonViTinhIDN = donViTinhID;
            newBO.SoLuong = 1;
            newBO.ThanhTienTra = 0;
            TraHangBOCollection.Add(newBO);

            sapxep();
            TinhTien();

        }

        private void sapxep()
        {

            int length = TraHangBOCollection.Count;

            for (int i = 0; i < length; i++)
            {
                TraHangBOCollection[i].STT0 = (i + 1);
            }

            bdSourcePhieuNhapChiTiet.DataSource = TraHangBOCollection;
        }

        private void TinhTien()
        {
            double tongso = 0;
            double thanhtien = 0;
            double tongtien = 0;

            int length = TraHangBOCollection.Count;

            for (int i = 0; i < length; i++)
            {
                tongso = tongso + StaticUtil.GetDouble(TraHangBOCollection[i].SoLuong, 0);
                thanhtien = thanhtien + StaticUtil.GetDouble(TraHangBOCollection[i].ThanhTienTra, 0);
            }

            tongtien = thanhtien;
            spinEditSoLuongTraLai.Value = (decimal)tongso;
            spinEditThanhTienTraLai.Value = (decimal)tongtien;
        }

        private void DeleteMatHang()
        {

            if (MessageBox.Show("Bạn có muốn xóa Mặt Hàng và Đơn vị tính này không? ", "Cảnh báo!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                int _idPhieuNhap = StaticUtil.GetInt(this.grdViewPhieuNhapChiTiet.GetFocusedRowCellValue("STT0"), -1);

                if (_idPhieuNhap >= 0)
                {
                    TraHangBOCollection.RemoveSTT(_idPhieuNhap);
                }                
                sapxep();
                TinhTien();
            }
        }

        private int kiemtraLuu()
        {
            int tempkiemtra = 1;
            string strError = "";

            if (lookUpEditNhaCungCap.EditValue == null)
            {
                tempkiemtra = 0;
                strError = "Chưa chọn Khách hàng";
            }

            if (txtMaSo.Text.Trim() == "")
            {
                tempkiemtra = 0;
                strError = strError + " ;Chưa nhập Mã số";
            }

            if (tempkiemtra == 0)
                MessageBox.Show(strError, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return tempkiemtra;
        }



        #endregion function

        private void txtTimkiem_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyData == Keys.Enter)
            {
                grdViewMatHang.Focus();
            }
        }

        private void grdViewMatHang_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyData == Keys.Enter)
            {
                UpdatePhieuNhap();
            }
        }
    }
}